// Package auth
// @Author zhongxc
// @Date 2024/7/30 10:02:00
// @Desc
package auth

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
	"vben-api/pkg/cache"
	"vben-api/pkg/svc"
	"vben-api/pkg/util"
	common "vben-common"
)

func JWTAuthMiddleware(svcCtx *svc.ServiceContext) func(c *gin.Context) {
	return func(c *gin.Context) {
		r := common.NewResult()

		expireAt := time.Duration(svcCtx.Config.JwtConfig.CreatedExpireAt)
		signKey := svcCtx.Config.JwtConfig.SignKey
		refreshSignKey := svcCtx.Config.JwtConfig.RefreshSignKey

		jwtAuth := util.NewJwtUtil(expireAt, signKey, refreshSignKey, cache.Rc)
		err := jwtAuth.TokenValid(c.Request)
		if err != nil {
			svcCtx.ResetUserInfo()
			c.JSON(http.StatusUnauthorized, r.Fail(401, "token鉴权未通过，请通过token授权接口重新获取token"))
			c.Abort()
			return
		}

		accessDetails, err := jwtAuth.ExtractTokenMetadata(c.Request)
		if err != nil {
			svcCtx.ResetUserInfo()
			c.JSON(http.StatusUnauthorized, r.Fail(401, "token鉴权未通过，请通过token授权接口重新获取token"))
			c.Abort()
			return
		}

		_, err = jwtAuth.FetchAuth(accessDetails)
		if err != nil {
			c.JSON(http.StatusUnauthorized, r.Fail(401, "token鉴权未通过，请通过token授权接口重新获取token"))
			return
		}

		c.Set("userinfo", accessDetails)
		svcCtx.SetUserInfo(accessDetails.UserId, accessDetails.Username)
		c.Next()
	}

}
